package com.suse.service.view.edu.controller;

import cn.hutool.core.util.ObjectUtil;
import com.suse.common.config.response.ApiException;
import com.suse.common.config.response.R;
import com.suse.common.util.jwt.JwtUtil;
import com.suse.model.dto.CourseDto;
import com.suse.model.dto.UserDto;
import com.suse.service.view.edu.model.param.CourseQueryParam;
import com.suse.service.view.edu.service.CourseService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程 前端控制器
 * </p>
 *
 * @author 辜玉彬
 * @since 2022-08-16
 */
@Api(tags = "课程接口")
@RestController
@RequestMapping("/course")
public class CourseController {

    @Resource
    private CourseService courseService;

    /**
     * 前台页面查询参数应该放在 URL 上传输
     * @param courseQueryParam 课程查询参数
     * @return R
     */
    @ApiOperation(value = "获取课程列表")
    @GetMapping("/list")
    public R getCourseList(CourseQueryParam courseQueryParam) {
        return courseService.getCourseList(courseQueryParam);
    }

    @ApiOperation(value = "通过ID获取课程详情")
    @GetMapping("/detail/{id}")
    public R getCourseDetailById(@PathVariable("id") String id) {
        return courseService.getCourseDetailById(id);
    }

    /**
     * 通过ID获取课程数据传输对象
     * @param id ID
     * @return R
     */
    @GetMapping("/inner/dto/{id}")
    public CourseDto getCourseDtoById(@PathVariable("id") String id) {
        return courseService.getCourseDtoById(id);
    }

    @ApiOperation(value = "判断课程是否已收藏")
    @GetMapping("/auth/hasCollect/{courseId}")
    public R hasCollect(@PathVariable("courseId") String courseId, HttpServletRequest request) {
        String token = request.getHeader("token");
        UserDto userDto = JwtUtil.parseToken(token, UserDto.class);
        if (ObjectUtil.isNull(userDto)) {
            throw new ApiException("未登录或登录已过期，请重新登录！");
        }
        String userId = userDto.getId();
        return courseService.hasCollect(courseId,userId);
    }

    @ApiOperation(value = "获取我的课程收藏列表")
    @GetMapping("/auth/my-collect-list")
    public R getMyCollectList(HttpServletRequest request) {
        String token = request.getHeader("token");
        UserDto userDto = JwtUtil.parseToken(token, UserDto.class);
        if (ObjectUtil.isNull(userDto)) {
            throw new ApiException("未登录或登录已过期，请重新登录！");
        }
        String userId = userDto.getId();
        return courseService.getMyCollectList(userId);
    }

    @ApiOperation(value = "通过关键字获取课程名称列表")
    @GetMapping("/nameList/{key}")
    public R getNameListByKey(@PathVariable("key") String key) {
        List<Map<String,String>> nameList = courseService.getNameListByKey(key);
        return R.success(nameList);
    }

}

